#include "videoBlobDetector.h"


//--------------------------------------------------------------
void videoBlobDetector::setup(int w, int h){	
	
	width 		= w;
	height 		= h;
	grayTemp.allocate(width,height);
	videoImageGray.allocate(width,height);
	videoImageColor.allocate(width, height);
	cornerMaskImage.loadImage("mask.png");
	cornerMaskImage.setImageType(OF_IMAGE_GRAYSCALE);
	cornerMaskImage.resize(width, height);
	cornerMaskCv.allocate(width, height);
	cornerMaskCv.setFromPixels(cornerMaskImage.getPixels(),width, height);
	
	maxBlobSize = 320*240;
	minBlobSize = 200;
	nBlobs = 0;
}


//--------------------------------------------------------------
void videoBlobDetector::update(ofCvColorImage video){
	videoImageColor = video;
	videoImageGray.setFromColorImage(video);
	videoImageGray -= cornerMaskCv;
	videoImageGray.threshold(20);
	
	videoImageGray.median_3x3();
	
	contourFinder.findContours(videoImageGray, minBlobSize,maxBlobSize, MAX_NUM_BLOBS, true);
}


//--------------------------------------------------------------
void videoBlobDetector::takeSnapshot(){
	nBlobs = contourFinder.nBlobs;
	if (contourFinder.nBlobs > 0){		
		for (int i = 0; i < contourFinder.nBlobs; i++){
			// for all non-hole contours - 
			if (contourFinder.blobs[i].hole == false){
				grayTemp.set(0); // set the image to black
				//---------------------------------------- draw the blob
				grayTemp.draw(contourFinder.blobs[i], 255);
			 	//---------------------------------------- draw ALL the holes
			 	//---------------------------------------- 
			 	for (int j = 0; j < contourFinder.nBlobs; j++){
			 		if (contourFinder.blobs[j].hole == true)
					grayTemp.draw(contourFinder.blobs[j], 0);
				}
			 // finally combine the mask, the video image into a vidBlob;
			 vidBlob[i].set(contourFinder.blobs[i], videoImageColor, grayTemp);
			 }
		}	
	}
}

//--------------------------------------------------------------
void videoBlobDetector::draw(){
}

//--------------------------------------------------------------
void videoBlobDetector::drawDetection(float x, float y){
	glPushMatrix();
	glTranslatef(x,y,0);
	contourFinder.draw();
	glPopMatrix();
}
